package com.ksck.logoDesign.app.network.request

import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.SPUtils
import com.gtxc.kotlinmvvm.config.Config
import okhttp3.*
import java.io.IOException
import java.lang.Exception

/**
 * Created by houzhanlei
 * 2020/7/24
 * 为自己代码负责
 * 默认参数拦截器
 */
class ParamInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response? {
        //偷天换日
        try {
            val oldRequest: Request = chain.request()

            //拿到拥有以前的request里的url的那些信息的builder
            val builder: HttpUrl.Builder = oldRequest
                .url()
                .newBuilder()

            //得到新的url（已经追加好了参数）
            val newUrl: HttpUrl = builder
                .addQueryParameter("version_name", AppUtils.getAppVersionName())
                .addQueryParameter("version_code", AppUtils.getAppVersionCode().toString())
                .build()
            var newRequest: Request?
            //利用新的Url，构建新的request，并发送给服务器
                newRequest = oldRequest
                    .newBuilder()
                    .header("Accept-Encoding", "identity")
                    .addHeader("Connection", "close")
                    .url(newUrl)
                    .header(
                        "token",
                        SPUtils.getInstance().getString(Config.HTTP_TOKEN_KET)
                    ).build()
            return chain.proceed(newRequest)

        } catch (e: Exception) {
            e.printStackTrace()
        }
        return chain.proceed(chain.request())

    }
}